# SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
# SPDX-License-Identifier: Mulan PSL v2
#!/usr/bin/env bash

#
#脚本调用方式：
#   cd xxx/xxx/xxx/packages/issp_ui/ui/
#   chmod +x install.sh
#   ./install.sh /target/web/ui/
#
#注意：
#   该脚本只能执行时cwd必须是当前前端目录！即调用时需要先手动cd到ui目录
#

#外部需要把目标路径传进来
WEBROOT="${1}"

if [ -z "${WEBROOT}" ]; then
    echo "missing parameter WEBROOT"
    exit 1
fi

if [ ! -d "${WEBROOT}" ]; then
    mkdir -p "${WEBROOT}"
fi

# 记录原来的环境变量，安装完成后，需要恢复环境变量
OLD="${PATH}"
CURRENT_PWD="$(cd `dirname $0`; pwd)"

# 进入lib目录, 并解压 node yarn sfx2 工具
cd lib
tar -xzf node-v10.15.0-linux-x64.tar.gz
tar -xzf yarn-0.21.3-linux-x86_64.tar.gz
tar -xzf sfx-v2.3.3.tar.gz
cd ..

# sfx目录名称
SFX2="sfx-v2.3.3"

# 添加环境变量
echo "add lib to path. node, npm, yarn, sfx..."
NEW="${CURRENT_PWD}/lib/node-v10.15.0-linux-x64/bin/:${PATH}"
export PATH=${NEW}
NEW="${CURRENT_PWD}/lib/yarn-0.21.3-linux-x86_64/bin/:${PATH}"
export PATH=${NEW}
NEW="${CURRENT_PWD}/lib/${SFX2}/bin/:${PATH}"
export PATH=${NEW}

function reset_env
{
    # 还原环境变量
    echo "reset env path"
    export PATH="${OLD}"
}

# 添加可执行权限
echo "chmod node, npm, phantomjs"
chmod +x ./lib/node-v10.15.0-linux-x64/bin/*
chmod +x ./lib/node-v10.15.0-linux-x64/lib/node_modules/npm/bin/*
rm -rf ./lib/node-v10.15.0-linux-x64/bin/npm
ln -s ../lib/node_modules/npm/bin/npm-cli.js ./lib/node-v10.15.0-linux-x64/bin/npm
chmod +x ./lib/yarn-0.21.3-linux-x86_64/bin/*
chmod +x ./lib/${SFX2}/bin/*

# 删除掉 sf-vue-component，去拿最新的
echo "remove sf-vue-components. please wait..."
rm -rf node_modules/sf-vue-component/

# 清除缓存
echo "yarn cache clean"
yarn cache clean

# 安装项目
echo "[project] yarn install, it will cost a lot of time. please wait..."
yarn install
if [ $? -ne 0 ]; then
    echo "[project] yarn install error!"
    reset_env;
    exit 1
fi

# 校验代码eslint
echo "[project] eslint. checklist checking..."
node ./lib/${SFX2}/bin/sfx2 eslint
if [ $? -ne 0 ]; then
    echo "[project] sfx2 eslint error!"
    reset_env;
    exit 1
fi

# 开始部署生成UI代码
echo "[project] build dist..."
node ./lib/${SFX2}/bin/sfx2 build
node ./lib/${SFX2}/bin/sfx2 build --config=theme.sfx.config.js

if [ $? -ne 0 ]; then
    echo "[project] sfx2 build error!"
    reset_env;
    exit 1
fi

# 把生成的文件拷贝到安装目录
echo "coping file to target: ${WEBROOT}"
rm -rf "${WEBROOT}"/*
cp -rf dist/* "${WEBROOT}"/
if [ $? -ne 0 ]; then
    echo "copy to INSTALLROOT error!"
    exit 1
fi
echo "copy file success"

reset_env;

# clean
echo "clean temp file"
rm -rf archive.tar sfx.git/ dist/

echo "install success"
